package 线程通信;

public class Acount {
//    无用的卡号
    private String cardID ;
    private double money ;

//    取钱方法
    public synchronized void pullMoney(double money) {

//        获取当前取钱人的名字
        String name = Thread.currentThread().getName();

        try {
//            如果账户有钱，取走；没有则等待，唤醒其他线程来存钱
            if (this.money >= money) {
                this.money -= money;
                System.out.println(name + "来取钱,取走了:" + money+",剩余:"+this.money);

//                唤醒其他线程
                this.notifyAll();
//                当前线程等待
                this.wait();
            } else {
                this.wait();
                this.notifyAll();
            }
        }catch (Exception e) {
            System.out.println(name+"取钱过程中出现了错误");
        }
    }

//    存钱方法
    public synchronized void pushMoney(double money) {

//        获取存钱人名字
        String name = Thread.currentThread().getName();

        try {
//            如果账户有钱就不存了，唤醒其他线程取钱，自己等待
            if (this.money > 0 ) {
                this.notifyAll();
                this.wait();
            }else {
                this.money += money;
                System.out.println(name+"来存钱，当前余额:"+this.money);
                this.notifyAll();
                this.wait();
            }
        }catch (Exception e) {
            System.out.println(name+"来存钱，遇到错误");
        }
    }



    public Acount() {
    }

    public Acount(String cardID, double money) {
        this.cardID = cardID;
        this.money = money;
    }

    public String getCardID() {
        return cardID;
    }

    public void setCardID(String cardID) {
        this.cardID = cardID;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}
